

var WinesRouter = Backbone.Router.extend({
    initialize: function () {
        $('#header').html(new HeaderView().render().el);
    },

    routes: {
        "": "list",
        "wines/new": "newWine",
        "wines/:id": "wineDetails"
    },

    list: function () {
        this.before();
    },

    wineDetails: function (id) {
        this.before(function () {
            var wine = winesrouter.wineList.get(id);
            winesrouter.showView('#content', new WineDetailsView({ model: wine }));
        });
    },

    newWine: function () {
        this.before(function () {
            winesrouter.showView('#content', new WineDetailsView({ model: new Wine() }));
        });
    },

    showView: function (selector, view) {
        if (this.currentView)
            this.currentView.close();
        $(selector).html(view.render().el);
        this.currentView = view;
        return view;
    },

    before: function (callback) {
        if (this.wineList) {
            if (callback) callback();
        } else {
            this.wineList = new WineCollection();
            this.startPollings();
            if (callback) callback();
        }
    },

    startPollings: function () {
        //see: https://github.com/uzikilon/backbone-poller
        var options = {
            // default delay is 1000ms
            delay: 10000,
            // condition for keeping polling active (when this stops being true, polling will stop)
            condition: function (model) {
                return true;
            },
            // callback to execute when the condition function is not true anymore, or when calling stop()
            complete: function () {

            },
            // callback to execute on every successful fetch
            success: function () {
                $('#sidebar').html(new WineListView({ model: winesrouter.wineList }).render().el);
            },
            // callback to execute on fetch error
            error: function () {
                console.error('oops! something went wrong');
            }

            // data to be passed to a collection fetch request
            //data: { fields: "*", sort: "name asc" }
        };
        this.poller = PollingManager.getPoller(this.wineList, options);
        this.poller.start();
    }
});
